<template>
  <zy-list-page-layout>
    <!-- 搜索区域 -->
    <template #search>
      <zy-query-form :query-params="queryParams" @query="handleQuery" @reset="resetQuery">
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="queryParams.roleName"
            placeholder="请输入角色名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input
            v-model="queryParams.roleCode"
            placeholder="请输入角色编码"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="角色类型" prop="roleType">
          <el-select v-model="queryParams.roleType" placeholder="请选择角色类型" clearable>
            <el-option label="系统角色" value="SYSTEM" />
            <el-option label="业务角色" value="BUSINESS" />
            <el-option label="自定义角色" value="CUSTOM" />
          </el-select>
        </el-form-item>
      </zy-query-form>
    </template>

    <!-- 操作按钮区域 -->
    <template #action>
      <el-button type="primary" @click="handleAdd"> 新增角色 </el-button>
    </template>

    <!-- 表格区域 -->
    <template #table>
      <zy-pagination-table
        ref="paginationTableRef"
        :query="getRoleListApi"
        :query-params="queryParams"
        :auto-load="false"
        v-model:data="roleList"
        v-model:total="total"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="roleName" label="角色名称" min-width="120" />
        <el-table-column prop="roleCode" label="角色编码" min-width="120" />
        <zy-table-dict-column
          prop="roleType"
          label="角色类型"
          width="120"
          :dict-options="roleTypeOptions"
          :tag-type-map="{ SYSTEM: 'danger', BUSINESS: 'primary', CUSTOM: 'success' }"
          default-tag-type="primary"
        />
        <el-table-column prop="systemCode" label="系统编码" min-width="120" />
        <zy-table-dict-column
          prop="isEnable"
          label="状态"
          width="100"
          dict-type-code="YES_NO"
          :tag-type-map="{ 1: 'success', 0: 'danger' }"
          default-tag-type="success"
        />
        <el-table-column prop="createTime" label="创建时间" min-width="180" align="center" />
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)"> 编辑 </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </zy-pagination-table>
    </template>
  </zy-list-page-layout>

  <!-- 角色表单对话框 -->
  <Detail
    v-model:visible="dialogVisible"
    :role-data="currentRole"
    :is-edit="isEdit"
    @success="handleSuccess"
  />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import {
  ElMessage,
  ElMessageBox,
  ElInput,
  ElButton,
  ElTableColumn,
  ElFormItem,
  ElSelect,
  ElOption
} from 'element-plus'
import { getRoleListApi, deleteRoleApi, SysRole, RoleQueryParams } from '@/api/system/role'
// Business 组件已全局注册，无需导入
import Detail from './Detail.vue'

// 响应式数据
const total = ref(0)
const roleList = ref<SysRole[]>([])
const dialogVisible = ref(false)
const currentRole = ref<SysRole>()
const isEdit = ref(false)

const paginationTableRef = ref()

// 查询参数
const queryParams = reactive<RoleQueryParams>({
  pageNum: 1,
  pageSize: 10,
  roleName: '',
  roleCode: '',
  roleType: '',
  systemCode: ''
})

// 角色类型选项
const roleTypeOptions = [
  { label: '系统角色', value: 'SYSTEM' },
  { label: '业务角色', value: 'BUSINESS' },
  { label: '自定义角色', value: 'CUSTOM' }
]

// 生命周期
onMounted(() => {
  nextTick(() => {
    if (paginationTableRef.value) {
      paginationTableRef.value.loadData()
    }
  })
})

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  if (paginationTableRef.value) {
    paginationTableRef.value.handleQuery()
  }
}

// 重置搜索
const resetQuery = () => {
  queryParams.roleName = ''
  queryParams.roleCode = ''
  queryParams.roleType = ''
  queryParams.systemCode = ''
  queryParams.pageNum = 1
  if (paginationTableRef.value) {
    paginationTableRef.value.resetQuery()
  }
}

// 新增角色
const handleAdd = () => {
  isEdit.value = false
  currentRole.value = undefined
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row: SysRole) => {
  isEdit.value = true
  currentRole.value = { ...row }
  dialogVisible.value = true
}

// 删除角色
const handleDelete = async (row: SysRole) => {
  try {
    await ElMessageBox.confirm('确认删除该角色吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    if (!row.roleId) {
      ElMessage.error('角色ID不能为空')
      return
    }

    const result: any = await deleteRoleApi(row.roleId)
    if (result === true || result.data === true) {
      ElMessage.success('删除成功')
      if (paginationTableRef.value) {
        paginationTableRef.value.loadData()
      }
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除角色失败:', error)
      ElMessage.error('删除角色失败')
    }
  }
}

// 表单提交成功回调
const handleSuccess = () => {
  if (paginationTableRef.value) {
    paginationTableRef.value.loadData()
  }
}
</script>
